<?php
/**
 * （FBA/海外仓）发货单需求审查确认
 * (model)
 */

namespace App\Models\Delivery;

use Encore\Admin\Facades\Admin;
use App\Func\UploadFile;
use Illuminate\Database\Eloquent\Model;
class DeliveryReview extends Model{

    protected $table = 'd_delivery_review';

    protected $guarded = [];

    /**
     * 文件类型
     */
    const TYPE_FBA = 1; //FBA
    const TYPE_WAREHOUSE = 2; //海外仓
    public static $_type = [
        self::TYPE_FBA       => 'FBA',
        self::TYPE_WAREHOUSE => '海外仓'
    ];

    public static $_status = [
        1 => '未确认',
        2 => '已确认',
    ];

    public static $_isFnsku = [
        1 => '是',
        2 => '否',
    ];

    public static function fileDir($type,$time){
        return 'deliveryReview'.DIRECTORY_SEPARATOR.$type.DIRECTORY_SEPARATOR.date('Ymd',$time);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            if(!Admin::user()->isRole('administrator')){
                if($model->status == 2){
                    throw new \Exception('需求文件已确认,无法删除!');
                }
            }
            $uf = UploadFile::getInit();
            $fileDir = self::fileDir($model->type,strtotime($model->created_at));
            $flag = $uf->delFile($fileDir.DIRECTORY_SEPARATOR.$model->file_name);
            if(!$flag){
                throw new \Exception('删除失败!');
            }
            if($model->tag_status == 2){
                $uf->delFile($fileDir.DIRECTORY_SEPARATOR.$model->tag_name);
            }
        });
    }
}
